package org.fing.edu.uy.esbadp.mechanism.monitor;

import java.io.File;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.fing.edu.uy.esbadp.constants.EsbAdpPropertyConfig;
import org.fing.edu.uy.esbadp.core.compare.wsdl.WsdlDiff;
import org.fing.edu.uy.esbadp.core.entity.DMRegisteredService;
import org.fing.edu.uy.esbadp.core.interfaces.ICompareWsdl;
import org.fing.edu.uy.esbadp.core.interfaces.IMechanismMonitor;
import org.fing.edu.uy.esbadp.core.registry.RegistryManager;
import org.fing.edu.uy.esbadp.modules.adpMotorMonitor.wsdl.CompareWsdl;
import org.fing.edu.uy.esbadp.modules.adpMotorMonitor.wsdl.StoreWsdl;
import org.fing.edu.uy.esbadp.utils.PathEvaluate;

public class MechanismMonitorServiceContractChange implements IMechanismMonitor {
	
	private static java.util.logging.Logger logger = Logger.getLogger(MechanismMonitorServiceContractChange.class.getSimpleName());

	@Override
	public Object getMonitorValue(DMRegisteredService service) {
		// Compare WSDL and Store
		WsdlDiff wsdlDiff = null;
		String pathRelative = RegistryManager.getInstance().getAdpConfigProperty(EsbAdpPropertyConfig.pathWSDLStore, "/esbadp/wsdl");
		String tmpPath = "file:///" + PathEvaluate.evaluatePath(pathRelative);
		String tmpFileName = String.valueOf(service.getServiceID());
		String wsdlURL = service.getEndPointURL() + "?wsdl";

		try{
			URL url0 = new URL(tmpPath + "/" + tmpFileName + ".xml");
			URL url1 = new URL(wsdlURL);
	
			// si ya existe un archivo antiguo persitido en disco comparo
			if (new File(new URL(tmpPath + "/" + tmpFileName + ".xml").toURI()).exists()) {
				ICompareWsdl iCompareWsdl = new CompareWsdl();
				wsdlDiff = (WsdlDiff) iCompareWsdl.compareDefinitions(url0, url1);
			}

			if(wsdlDiff == null || wsdlDiff.getOperations().size() > 0){
				new File(new URL(tmpPath).toURI()).mkdirs();
				StoreWsdl.storeWsdl(wsdlURL, tmpPath, tmpFileName);
			}
		}catch (Exception ex) {
			logger.log(Level.SEVERE,"The service url is incorrect. Please check.", ex);
		}
		return wsdlDiff;
	}
	
}
